# Greeting people (with functions)
# Much better!
def greet(your_name):
print(f"Nice to meet you, {your_name}!")
greet("Alice")
greet("Bob")
greet("Danilo")Nice to meet you, Alice!
Nice to meet you, Bob!
Nice to meet you, Danilo!
Because copy-pasting code is so last semester
February 07, 2025
def)return# Greeting people (without functions)
# Don't do this at home!
print("Nice to meet you, Alice!")
print("Nice to meet you, Bob!")
print("Nice to meet you, Charlie!")
print("Nice to meet you, Danilo!")
print("Nice to meet you, Emily!")
print("Nice to meet you, Frank!")
print("Nice to meet you, George!")
# ... repeats 993 more times ...Maybe there’s a better way to do this? 🤔
print(), type(), np.mean(), plt.hist() are all functions you’ve used before! 🤓# Greeting people (with functions)
# Much better!
def greet(your_name):
print(f"Nice to meet you, {your_name}!")
greet("Alice")
greet("Bob")
greet("Danilo")Nice to meet you, Alice!
Nice to meet you, Bob!
Nice to meet you, Danilo!
DRY principle: Don’t Repeat Yourself 😉
def keyword. Tells Python: “We are defining a function now”function_name). Choose a descriptive name (e.g., greet, calculate_age, etc)(). Enclose inputs the function needs. Empty () means no inputsparameter). A placeholder for the values the function will receive. Can be multiple, separated by commasparameter=argument). The actual values that will be passed to the function.: Ends the function header. Don’t forget it!return statement (optional). What the function sends back. If absent, function returns None. Indent it too!say_greeting(name)return statement?message_alice = say_greeting("Alice")?say_greeting?greeting_type="Hello" part? What does it mean?message_bob = get_greeting("Bob") and then print(message)?We can use the result in further calculations!
More about the return statement here
calculate_area function below 👇length=5 and width=4, and print the resultname before greeting_typereturn statement)lambda arguments: expression
lambda x, y: x + ydistance = speed * timespeed=100 and time=2message from outside:message has disappeared!global keywordIf you want to change a global variable inside a function, you need to use the global keyword
This tells Python: “Hey, I’m talking about the global variable here!”
Let’s see an example:
global_greeting is not passed as an argument to the function?print, sum, list)def f(x):, def function1():, def sum():, def cR@zY_fUnC(): 👎def calculate_area():, def greet_user():, def get_data(): 👍docstrings to document your functions! 📚""" or ''')return, and more!IndentationError!
print instead of returnreturn a value when you need onedef keyword, name, parameters, body, return, and indentationglobal keyword to change global variables inside functionsreturn statementsprint instead of returnreturn inside loops or if statements